package com.financing.wap.web.filter;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.service.ILogsService;

/**
 * Servlet Filter implementation class AccessFilter
 */
@Component(value="sysLogFilter")
public class SysLogFilter implements Filter,ApplicationContextAware{
	
	private Logger log = Logger.getLogger(this.getClass());
	
	private String msgStatusURI = "/wap/api/message/msgStatus";
	
	@Autowired
	protected ILogsService logsServiceImpl;
    /**
     * Default constructor. 
     */
    public SysLogFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		
		String URI = httpRequest.getRequestURI();
		Session session = SessionUtil.getSession(true);
		DstUserInfoDTO loginUser = session.getUser();
			StringBuffer stringBuffer = new StringBuffer().append("{");
			@SuppressWarnings("unchecked")
			Map<String,Object> params = request.getParameterMap();
			
			Set<Entry<String,Object>> set = params.entrySet();
			
			for(Iterator<Entry<String,Object>> it = set.iterator();it.hasNext();){
				Entry<String,Object> tmp = it.next();
				//统一特殊处理  新增文章内容不如库
				if(!(tmp.getKey().toLowerCase().trim().equals("password")||tmp.getKey().equals("dstArticleContent"))){
					stringBuffer.append(tmp.getKey());
					stringBuffer.append("=");
					String[] values = (String[]) tmp.getValue();
					for(String value :values){
						stringBuffer.append(value);
						stringBuffer.append(",");
					}
				}
				
			}
			stringBuffer.append("}");
			stringBuffer.append("; from IP:")
						.append(getRemoteHost(httpRequest));
			
			if(!msgStatusURI.equals(URI)){
				try {
					if(loginUser!= null){
						logsServiceImpl.addLog(URI, stringBuffer.toString(), loginUser.getUserWechatOpenid());
					}else{
						logsServiceImpl.addLog(URI, stringBuffer.toString(), "system");
					}
				} catch (SQLException e) {
					log.warn("Write log error !",e);
				}
			}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		logsServiceImpl = (ILogsService) applicationContext.getBean("logsServiceImpl");
		
	}
	
	public String getRemoteHost(javax.servlet.http.HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}

}
